<template>
  <div class="container">
    <div class="left-tree">
      <el-tree
        :data="treeData"
        :props="treeProps"
        node-key="id"
        ref="treeRef"
        @node-click="handleTreeClick"
        :default-selected-keys="[defaultSelectedId]"
        :default-expanded-keys="[defaultExpandedId]"
        highlight-current
        :filter-node-method="filterNode"
        style="width: 100%"
      ></el-tree>
    </div>
    <div class="right-content">
      <!-- 右侧表单：日期选择器默认显示近一个月 -->
      <el-form :model="queryParams" :inline="true" class="query-form">
        <el-form-item label="时间段：">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="水质状况：">
          <el-select
            v-model="queryParams.qualitystate"
            placeholder="请选择水质状况"
            style="width: 100%"
          >
            <el-option
              v-for="item in dict.type.trace_quality_state"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" @click="handleReset"
            >重置</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-download"
            @click="handleExport"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        id="selectTable"
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="sampletime" label="监测时间"></el-table-column>
        <el-table-column prop="qualitystate" label="水质状况">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.trace_quality_state"
              :value="scope.row.qualitystate"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="backdropexvalue"
          label="背景水"
        ></el-table-column>
        <el-table-column prop="currentexvalue" label="当前水"></el-table-column>
        <el-table-column
          prop="peakdiscrepancy"
          label="峰值差异"
        ></el-table-column>
        <el-table-column prop="exdiscrepancy" label="Ex差异"></el-table-column>
        <el-table-column prop="emdiscrepancy" label="Em差异"></el-table-column>
        <el-table-column
          prop="comparisonresult"
          label="对比结果"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="viewChart(scope.row)"
              >查看图表</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="slot, total, sizes, prev, pager, next, jumper"
        :total="total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="handleQuery"
        />
      </el-pagination>
    </div>

    <!-- ECharts图表弹框 -->
    <el-dialog
      :title="chartTitle"
      :visible.sync="chartDialogVisible"
      width="800px"
    >
      <div ref="chartContainer" style="width: 100%; height: 400px"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chartDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from "echarts";
import tableToExcel from "@/utils/tableToExcel";
import { getTreeSelect, getMonitorDataPage } from "@/api/traceability";

export default {
  name: "WaterSourceTracing",
  dicts: ["trace_quality_state"],
  data() {
    return {
      treeData: [],
      treeProps: {
        children: "children",
        label: "name",
        disabled: "hasChildren", // 有子级的父节点禁用
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeRange: this.getDefaultDateRange(), // 关键：初始化默认近一个月
        waterQuality: "",
        selectedTreeId: null,
      },
      tableData: [],
      total: 0,
      chartDialogVisible: false,
      chartTitle: "数据对比图表",
      myChart: null,
      defaultSelectedId: null,
      defaultExpandedId: null,
    };
  },
  mounted() {
    this.getTreeSelect();
  },
  methods: {
    /**
     * 核心方法：计算默认时间范围（近一个月：当前日期前30天 ~ 当前日期）
     * @returns {Array} [开始日期, 结束日期]（格式：yyyy-MM-dd）
     */
    getDefaultDateRange() {
      const end = new Date(); // 结束日期：当前日期
      const start = new Date(); // 开始日期：当前日期前30天
      start.setTime(start.getTime() - 30 * 24 * 60 * 60 * 1000); // 30天的毫秒数

      // 格式化日期为 yyyy-MM-dd（补0处理，避免出现 2024-9-1 这种格式）
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，补0到2位
        const day = String(date.getDate()).padStart(2, "0"); // 日期补0到2位
        return `${year}-${month}-${day}`;
      };

      return [formatDate(start), formatDate(end)];
    },

    // 获取树形数据并处理
    getTreeSelect() {
      getTreeSelect()
        .then((response) => {
          const flatData = response.data || [];
          this.treeData = this.buildTree(flatData);
          this.calcDefaultSelected();
          this.$nextTick(() => {
            if (this.defaultSelectedId && this.$refs.treeRef) {
              this.$refs.treeRef.setCurrentKey(this.defaultSelectedId);
              this.queryParams.selectedTreeId = this.defaultSelectedId;
              this.handleQuery(); // 初始化时用默认时间范围查询
            }
          });
        })
        .catch((err) => {
          console.error("获取树形数据失败：", err);
        });
    },

    // 构建树形结构（标记有子级的父节点）
    buildTree(flatData) {
      const nodeMap = {};
      const rootNodes = [];

      flatData.forEach((node) => {
        nodeMap[node.id] = { ...node, children: [], hasChildren: false };
      });

      flatData.forEach((node) => {
        const currentNode = nodeMap[node.id];
        const parentId = node.pid;

        if (parentId === "0") {
          rootNodes.push(currentNode);
        } else {
          const parentNode = nodeMap[parentId];
          if (parentNode) {
            parentNode.children.push(currentNode);
            parentNode.hasChildren = true; // 有子级的父节点标记为禁用
          }
        }
      });

      return rootNodes;
    },

    // 计算默认选中的叶子节点
    calcDefaultSelected() {
      if (this.treeData.length === 0) return;

      // 递归查找第一级根节点的最后一个叶子节点
      const findLastLeaf = (node) => {
        if (node.children && node.children.length > 0) {
          return findLastLeaf(node.children[node.children.length - 1]);
        } else {
          return node;
        }
      };

      const firstRootNode = this.treeData[0];
      const lastLeafNode = findLastLeaf(firstRootNode);

      this.defaultSelectedId = lastLeafNode.id;
      this.defaultExpandedId = firstRootNode.id;
    },

    // 节点点击事件（仅叶子节点可触发）
    handleTreeClick(data) {
      if (!data.hasChildren) {
        this.queryParams.selectedTreeId = data.id;
        this.handleQuery();
      }
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParams.pageNum = val;
      this.handleQuery();
    },

    // 查询（携带默认时间范围）
    handleQuery() {
      console.log("当前查询参数（含默认近一个月）：", this.queryParams);
      let query = {};
      if (
        this.queryParams.timeRange &&
        this.queryParams.timeRange.length === 2
      ) {
        query.startTime = this.queryParams.timeRange[0];
        query.endTime = this.queryParams.timeRange[1];
      }
      query.pageSize = this.queryParams.pageSize;
      query.pageNum = this.queryParams.pageNum;
      query.qualitystate = this.queryParams.qualitystate;
      query.devsn = this.queryParams.selectedTreeId;
      getMonitorDataPage(query)
        .then((response) => {
          this.tableData = response.rows || [];
          this.total = response.total || 0;
        })
        .catch((err) => {
          console.error("查询表格数据失败：", err);
          this.$message.error("数据加载失败，请重试");
        });
    },

    // 重置（恢复默认近一个月时间范围）
    handleReset() {
      this.queryParams.timeRange = this.getDefaultDateRange(); // 关键：重置时恢复默认时间
      this.queryParams.waterQuality = "";
      if (this.defaultSelectedId && this.$refs.treeRef) {
        this.$refs.treeRef.setCurrentKey(this.defaultSelectedId);
        this.queryParams.selectedTreeId = this.defaultSelectedId;
        this.handleQuery();
      }
    },

    // 导出功能
    handleExport() {
      tableToExcel.getExcel("#selectTable", "溯源监测数据");
    },

    // 查看图表
    viewChart(row) {
      this.chartDialogVisible = true;
      this.$nextTick(() => {
        this.initChart(row);
      });
    },

    // 初始化ECharts图表
    initChart(row) {
      if (this.myChart) {
        this.myChart.dispose();
      }
      this.myChart = echarts.init(this.$refs.chartContainer);
      const option = {
        title: { text: "数据对比" },
        tooltip: { trigger: "axis" },
        legend: { data: ["Ex差异", "Em差异"] },
        xAxis: { type: "category", data: ["差异"] },
        yAxis: { type: "value" },
        series: [
          // { name: "峰值差异", data: [row.peakDiff, 0], type: "bar" },
          { name: "Ex差异", data: [row.exdiscrepancy, 0], type: "bar" },
          { name: "Em差异", data: [row.emdiscrepancy, 0], type: "bar" },
        ],
      };
      this.myChart.setOption(option);
    },

    // 节点过滤（可选）
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose();
    }
  },
};
</script>

<style scoped>
.container {
  display: flex;
  height: calc(100vh - 20px);
}

.left-tree {
  width: 200px;
  border-right: 1px solid #e6e6e6;
  padding: 10px;
}

.right-content {
  flex: 1;
  padding: 10px;
}

.query-form {
  margin-bottom: 10px;
}

/* 选中节点高亮 */
::v-deep
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  color: #409eff !important;
  font-weight: 500;
}

/* 禁用父节点样式 */
::v-deep .el-tree-node.is-disabled > .el-tree-node__content {
  color: #c0c4cc !important;
  cursor: not-allowed;
}
</style>
